package com.mizar.plugin.broadcast_cdt;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.Map;

import io.flutter.Log;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/**
 * BroadcastCdtPlugin
 */
public class BroadcastCdtPlugin implements FlutterPlugin, MethodCallHandler, EventChannel.StreamHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    public static final String LOCATION_INFO_INTENT = "com.huace.landstar.api.action";
    private FlutterPluginBinding flutterPluginBinding;
    private MethodChannel channel;
    private EventChannel eventChannel;
    private EventChannel.EventSink eventSink;
    // 是否监听电池状态改变
    private boolean isWatcher;
    private final BroadcastReceiver receiveLocationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (eventSink == null) {
                return;
            }
            if (intent == null) {
                return;
            }
            if (intent.getAction().equals(LOCATION_INFO_INTENT)) {
                Location location = intent.getParcelableExtra("location");
                if (location != null) {
                    Map<String, Object> result = new HashMap<>();
                    result.put("provider", location.getProvider());
                    result.put("latitude", Math.toDegrees(location.getLatitude()));
                    result.put("longitude", Math.toDegrees(location.getLongitude()));
                    result.put("altitude", location.getAltitude());
                    result.put("accuracy", location.getAccuracy());
                    // 板卡解算状态-1:搜星中 0:单点  1:SBAS 2:浮动 3:固定 4: 伪距差分
                    result.put("solveStatus", location.getExtras().get("solve_status"));
                    result.put("x_precision", location.getExtras().get("x_precision"));
                    result.put("y_precision", location.getExtras().get("y_precision"));
                    result.put("h_precision", location.getExtras().get("h_precision"));
                    result.put("key_neh_n", location.getExtras().get("key_neh_n"));
                    result.put("key_neh_e", location.getExtras().get("key_neh_e"));
                    result.put("key_neh_h", location.getExtras().get("key_neh_h"));
                    new Handler(Looper.getMainLooper()).post(() -> eventSink.success(JSON.toJSONString(result)));
                }
            }
        }
    };

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "broadcast_cdt_method_channel");
        channel.setMethodCallHandler(this);
        eventChannel = new EventChannel(flutterPluginBinding.getBinaryMessenger(), "broadcast_cdt_event_channel");
        eventChannel.setStreamHandler(this);
        this.flutterPluginBinding = flutterPluginBinding;
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        switch (call.method) {
            case "getPlatformVersion":
                result.success("Android " + android.os.Build.VERSION.RELEASE);
                break;
            case "startLocationReceiver":
                Log.i("receiveLocationBroadcastReceiver", "开启监听startLocationReceiver");
                if (!isWatcher) {
                    isWatcher = true;
                    flutterPluginBinding.getApplicationContext().registerReceiver(receiveLocationBroadcastReceiver, new IntentFilter(LOCATION_INFO_INTENT));
                }
                result.success(true);
                break;
            case "removeLocationReceiver":
                Log.i("receiveLocationBroadcastReceiver", "移除监听removeLocationReceiver...");
                if (isWatcher) {
                    isWatcher = false;
                    flutterPluginBinding.getApplicationContext().unregisterReceiver(receiveLocationBroadcastReceiver);
                }
                result.success(true);
                break;
            default:
                result.notImplemented();
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
        eventChannel.setStreamHandler(null);
        binding.getApplicationContext().unregisterReceiver(receiveLocationBroadcastReceiver);
    }

    @Override
    public void onListen(Object arguments, EventChannel.EventSink events) {
        eventSink = events;
    }

    @Override
    public void onCancel(Object arguments) {
        eventSink = null;
    }
}
